const express = require("express")
const md5 = require("md5")
const adminModel = require("../db/model/adminModel")
const jwt = require("../utils/jwt")
// 处理上传文件的中间件
const formidableMiddleware = require("express-formidable")
const router = express.Router()

const middleWare = formidableMiddleware({
  // 上传的文件存储的路径
  uploadDir: "./public/uploadDir",
  // 上传的文件保留后缀名
  keepExtensions: true,
})

const verifyTokenMiddleWare = async function (req, res, next) {
  const authorization = req.get("authorization")
  if (authorization) {
    const admin = await adminModel.findOne({ token: authorization })
    if (admin) {
      const result = jwt.decode(authorization)
      if (Date.now() < result.expires) {
        next()
        return
      }
    }
  }
  res.send({ success: false, msg: "token无效" })
}

//获取所有管理员资料用于前端渲染页面
router.get("/findAdmins", async (req, res) => {
  try {
    const result = await adminModel.find({}, { password: 0 })
    res.send({ success: true, msg: "管理员获取成功", data: result })
  } catch (err) {
    res.send({ success: false, msg: "管理员获取失败" })
  }
})

//验证管理员用户名是否重复
router.get("/findAdmin", async (req, res) => {
  const { username } = req.query
  const admin = await adminModel.findOne({ username })
  if (admin) {
    res.send({
      success: false,
      msg: "管理员用户名重复，请重新设置",
    })
  } else {
    res.send({ success: true, msg: "管理员用户名可用" })
  }
})

//添加新管理员
router.post(
  "/addAdmin",
  middleWare,
  verifyTokenMiddleWare,
  async (req, res) => {
    try {
      const { username, password } = req.fields
      await adminModel.create({ username, password: md5(password) })
      res.send({ success: true, msg: "添加成功" })
    } catch (err) {
      res.send({ success: false, msg: "添加失败" })
    }
  }
)

//删除一个管理员
router.post("/deleteAdmin", verifyTokenMiddleWare, async (req, res) => {
  const { id } = req.body
  try {
    await adminModel.deleteOne({ _id: id })
    res.send({ success: true, msg: "管理员删除成功" })
  } catch {
    res.send({ success: false, msg: "管理员删除失败" })
  }
})

//修改管理员密码
router.post("/updateAdmin", verifyTokenMiddleWare, async (req, res) => {
  const { id, password } = req.body
  try {
    const admin = await adminModel.updateOne(
      { _id: id },
      { $set: { password: md5(password) } }
    )
    res.send({ success: true, msg: "管理员密码修改成功" })
  } catch {
    res.send({ success: false, msg: "管理员密码修改失败" })
  }
})

module.exports = router
